package lib {
	import mx.controls.Image;
	import mx.managers.PopUpManager;
	import mx.containers.Box;
	import mx.core.Application;
	import mx.logging.*;
	import norbert.webapis.flickr.*;
	import flash.events.ProgressEvent;
	import flash.events.Event;
	import flash.geom.Point;

	public class PhotoImage extends Image {
		private static const logger: ILogger = Log.getLogger("lib.PhotoImage");
		
		public function PhotoImage() {
			addEventListener(Event.OPEN, onOpen);
			addEventListener(ProgressEvent.PROGRESS, onProgress);
			addEventListener(Event.COMPLETE, onComplete);
		}
		
		private var managr: Managr = Application.application as Managr;
		
		private var _photoSize: String = "square";
		[Bindable("photoSizeChanged")]
		public function get photoSize(): String {
			return _photoSize;
		}
		public function set photoSize(value: String): void {
			_photoSize = value;
		}
	
		private var _photo: Photo;
		[Bindable("photoChanged")]
		public function get photo(): Photo {
			return _photo;
		}
		public function set photo(value: Photo): void {
			_photo = value;
			if (photo) {
				if (photoSize == "square") {
					this.source = photo.sourceSquare;
				} else if (photoSize == "thumbnail") {
					this.source = photo.sourceThumbnail;
				} else if (photoSize == "small") {
					this.source = photo.sourceSmall;
				} else if (photoSize == "medium") {
					this.source = photo.sourceMedium;
				}
			}
		}
		
		private var progressBar: Box;
		private function onProgress(event: ProgressEvent): void {
			progressBar.width = width * event.bytesLoaded / event.bytesTotal;
		}
		private function onOpen(event: Event): void {
			if (progressBar == null) {
				progressBar = new Box();
				progressBar.height = 10;
				var point: Point = new Point(0, height - progressBar.height);
				point = localToGlobal(point);
				progressBar.x = point.x;
				progressBar.y = point.y;
				progressBar.setStyle("backgroundColor", "#0063DC");
			}

			progressBar.width = 0;
			PopUpManager.addPopUp(progressBar, this);
		}
		private function onComplete(event: Event): void {
			PopUpManager.removePopUp(progressBar);
		}
	}
}